import struct
import socket
import numpy as np
from cv2 import cv2

bufsize = 1024

soc = None
host = '192.168.122.10'
port = 8080
img = None
cv2.namedWindow('main')

def run():
    global soc, img
    soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    soc.connect((host, port))
    lenb = soc.recv(4)
    le = struct.unpack('>I', lenb)[0]
    imb = b''
    while le > bufsize:
        t = soc.recv(bufsize)
        imb += t
        le -= len(t)
    while le > 0:
        t = soc.recv(le)
        imb += t
        le -= len(t)
    data = np.frombuffer(imb, dtype=np.uint8)
    img = cv2.imdecode(data, cv2.IMREAD_COLOR)

    while True:
        cv2.imshow('main', cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
        lenb = soc.recv(4)
        le = struct.unpack('>I', lenb)[0]
        imb = b''
        while le > bufsize:
            t = soc.recv(bufsize)
            imb += t
            le -= len(t)
        while le > 0:
            t = soc.recv(le)
            imb += t
            le -= len(t)
        data = np.frombuffer(imb, dtype=np.uint8)
        ims = cv2.imdecode(data, cv2.IMREAD_COLOR)
        img = img + ims
        cv2.waitKey(90)

if __name__ == '__main__':
    run()